import { ActionBase, ActionBaseOfCreep } from "../ActionBase";

 
/**
 * 放置site Action
 */
export class ActionDealSell  extends ActionBase<IActionCMD<"dealsell">>
{
    public execute(action: IActionCMD<"dealsell">): ActionCode 
    {
        const room = action.arg.entity;
        const coreentity = room.getEntity("CoreEntity");
        const arg  = action.arg.task;
        if(!coreentity.Terminal)
        {
            return 0;
        }
        const order = Game.market.getOrderById(arg.orderId);
        if(!order)
        {
            return 0;
        }
        const existnum =  coreentity.Terminal.store.getUsedCapacity(order.resourceType as ResourceConstant);

        if(coreentity.Terminal.cooldown  == 0)
        {
            if(arg.amount<=existnum)
            {
                // 终端资源充足
                const code = Game.market.deal(arg.orderId,existnum,coreentity.roomName);
                if(code == OK)
                {
                    arg.amount-=existnum;
                }
                else if(code != ERR_FULL)
                {
                    if(action.arg.task.taskid)
                    {
                        room.deleteTaskById(action.arg.task.taskid,"terminal");
                    }
                    return -2;
                }

            }
            else
            {
                // 终端资源不足
                // 是否能从storage调用
                const leftcount = arg.amount-existnum;
                if(coreentity.Storage)
                {
                    const storage_num = coreentity.Storage.store.getUsedCapacity(order.resourceType as ResourceConstant);
                    if(storage_num>=leftcount)
                    {
                        // 从storage调用
                        coreentity.transferResource(coreentity.Storage,coreentity.Terminal,[{resourceType:order.resourceType as ResourceConstant,amount:leftcount}],1);
                    }
                    else
                    {
                        const code = Game.market.deal(arg.orderId,existnum,coreentity.roomName);
                        if(code == OK)
                        {
                            arg.amount-=existnum;
                        }
                        else if(code != ERR_FULL)
                        {
                            if(action.arg.task.taskid)
                            {
                                room.deleteTaskById(action.arg.task.taskid,"terminal");
                            }
                            return -2;
                        }
                    }
                }
            }
        }
        return 0;
    }
}